var express = require("express");
var router = express.Router();
let {
  UserM,
  serveModel,
  cateModel,
  tagModel,
  socialModel,
} = require("../../modules/model");
const xlsx = require('xlsx');

router.get("/user", async (req, res) => {
  let data = await UserM.find();
  res.send({
    code: 200,
    data,
  });
});

//添加服务人员
router.post("/serve/add", async (req, res) => {
  await serveModel.create(req.body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});

//获取全部服务人员
router.get("/serve/list", async (req, res) => {
  let list = await serveModel.find();
  res.send({
    code: 200,
    list,
  });
});
//添加服务类型
router.post("/cate/add", async (req, res) => {
  await cateModel.create(req.body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});

//获取全部服务类型
router.get("/cate/list", async (req, res) => {
  let list = await cateModel.find();
  res.send({
    code: 200,
    list,
  });
});

//添加标签
router.post("/tag/add", async (req, res) => {
  await tagModel.create(req.body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});

//获取全部标签
router.get("/tag/list", async (req, res) => {
  let list = await tagModel.find();
  res.send({
    code: 200,
    list,
  });
});

//添加用户社交
router.post("/social/add", async (req, res) => {
  await socialModel.create(req.body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});
//获取全部用户社交
router.get("/social/list", async (req, res) => {
  let list = await socialModel.find();
  res.send({
    code: 200,
    list,
  });
});

//批量删除
router.post("/social/batchDelete", async (req, res) => {
  try {
    const { ids } = req.body;
    console.log("要删除的ID:", ids);

    if (!Array.isArray(ids) || ids.length === 0) {
      return res.json({
        code: 400,
        message: "无效的ID数组"
      });
    }

    const result = await socialModel.deleteMany({ 
      _id: { $in: ids.map(id => id.toString()) } 
    });

    console.log("删除结果:", result);

    if (result.deletedCount > 0) {
      res.json({
        code: 200,
        message: `成功删除 ${result.deletedCount} 条数据`
      });
    } else {
      res.json({
        code: 400,
        message: "未找到要删除的数据"
      });
    }
  } catch (error) {
    console.error("批量删除失败:", error);
    res.json({
      code: 500,
      message: "删除失败: " + error.message
    });
  }
});

// 添加批量导出接口
router.post("/social/batchExport", async (req, res) => {
    try {
        const { ids } = req.body;
        console.log("要导出的ID:", ids);

        if (!Array.isArray(ids) || ids.length === 0) {
            return res.status(400).json({
                code: 400,
                message: "无效的ID数组"
            });
        }

        // 获取选中的数据
        const list = await socialModel.find({ 
            _id: { $in: ids.map(id => id.toString()) } 
        });

        console.log("查询到的数据:", list);

        if (!list || list.length === 0) {
            return res.status(400).json({
                code: 400,
                message: "未找到要导出的数据"
            });
        }

        // 准备Excel数据
        const excelData = list.map((item, index) => ({
            '序号': index + 1,
            '头像URL': item.img || '',
            '姓名': item.name || '',
            'ID': item.userId || '',
            '真实姓名': item.realName || '',
            '手机号码': item.phone || '',
            '动态数量': item.dynamic || 0,
            '阅读量': item.read || 0,
            '关注': item.attention || 0,
            '粉丝': item.fans || 0,
            '点赞': item.upvote || 0,
            '收藏': item.collections || 0,
            '评论': item.comment || 0,
            '转发': item.transmit || 0
        }));

        // 创建工作簿和工作表
        const wb = xlsx.utils.book_new();
        const ws = xlsx.utils.json_to_sheet(excelData, {
            header: Object.keys(excelData[0])
        });

        // 设置列宽
        const colWidths = [
            { wch: 8 },  // 序号
            { wch: 50 }, // 头像URL
            { wch: 15 }, // 姓名
            { wch: 15 }, // ID
            { wch: 15 }, // 真实姓名
            { wch: 15 }, // 手机号码
            { wch: 12 }, // 动态数量
            { wch: 12 }, // 阅读量
            { wch: 10 }, // 关注
            { wch: 10 }, // 粉丝
            { wch: 10 }, // 点赞
            { wch: 10 }, // 收藏a
            { wch: 10 }, // 评论
            { wch: 10 }  // 转发
        ];``
        ws['!cols'] = colWidths;

        // 添加工作表到工作簿
        xlsx.utils.book_append_sheet(wb, ws, '社交数据');

        // 生成Excel文件Buffer
        const buffer = xlsx.write(wb, { 
            type: 'buffer', 
            bookType: 'xlsx',
            bookSST: false
        });

        // 设置响应头
        res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        res.setHeader('Content-Disposition', `attachment; filename=${encodeURIComponent('社交数据导出.xlsx')}`);
        
        // 发送文件
        res.send(buffer);

        console.log("导出成功");

    } catch (error) {
        console.error("导出失败:", error);
        res.status(500).json({
            code: 500,
            message: "导出失败: " + error.message
        });
    }
});

module.exports = router;
